package myJs.common

import myJs.Implicits._
import myJs.cps.Style
import myJs.myPkg.jquery.{$, JQuery}
import myJs.myPkg.reactHookForm._
import org.scalajs.dom.{Event, html}
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.{Fragment, React}
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.web.html._

import scala.scalajs.js

/**
 * Created by yz on 21/1/2022
 */
@react object PureTextareaCp {

  case class Props(useForm: UseFormRT,
                   registerOptions: RegisterOptions = RegisterOptions(),
                   showValidate: Boolean = true,
                   name: String = "", hasBv: Boolean = false, formJq: JQuery = $("#form"),
                   placeHolder: String = "", value: js.UndefOr[String] = js.undefined,
                   onChange: js.UndefOr[String => Unit] = js.undefined,
                   selfClassName: String = "",
                   rows: String = "3"
                  )

  val component = FunctionalComponent[Props] { props =>

    val valueOp = props.useForm.watch(props.name)

    useEffect(() => {
      valueOp.asInstanceOf[js.UndefOr[String]].foreach { v =>
        props.onChange.foreach(_ (v))
      }
    }, List(valueOp)
    )

    useEffect(() => {
      props.useForm.setValue(props.name, props.value)
    }, List(props.value)
    )

    Fragment(
      Controller(
        name = props.name,
        control = props.useForm.control,
        rules = props.registerOptions,
        render = (fieldR: FieldR) => {
          val field = fieldR.field
          textarea(style := Style(width = "100%"), className := s"form-control fillByName ${props.selfClassName}",
            name :=field.name, value := field.value.asInstanceOf[js.UndefOr[String]].toOption,
            placeholder := props.placeHolder, ref := field.ref, onChange := field.onChange,
            rows := props.rows
          )()
        }
      ),
      if (props.showValidate && props.useForm.formState.errors.deepDefinedAt(props.name)) {
        small(className := "help-block", props.useForm.formState.errors.deepGet(props.name).message)
      } else null
    )


  }

}
